package request

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"maya-service/config"
	"net/http"
	Url "net/url"
)

func DoRequest(method string, url string, data string, headers map[string]string) (res string, err error) {
	transport := &http.Transport{}
	if config.Conf.Env == "test" {
		proxyURL, err := Url.Parse("http://proxy.shengu.info:3883")
		if err != nil {
			fmt.Println(err)
		}
		transport.Proxy = http.ProxyURL(proxyURL)
	}
	client := &http.Client{
		Transport: transport,
	}

	req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(data)))
	if err != nil {
		fmt.Println(err.Error())
		return "", err
	}

	if keys := req.Header.Get("Content-Type"); len(keys) == 0 {
		req.Header.Set("Content-Type", "application/json")
	}

	for k, v := range headers {
		req.Header.Set(k, v)
	}

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println(err.Error())
		return "", err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return "", err
	}

	return string(body), nil
}
